<template>
  <div>
    <!-- //用户登录用到的弹出框-->
    <el-dialog title="登录" :visible.sync="$store.state.loginDialog">
      <el-form :model="Loginobj" :rules="rules" status-icon ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="userName">
          <el-input
            autocomplete="off"
            prefix-icon="el-icon-user-solid"
            placeholder="请输入账号"
            v-model="Loginobj.userName"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            autocomplete="off"
            prefix-icon="el-icon-view"
            placeholder="请输入密码"
            v-model="Loginobj.password"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getLogin('ruleForm')">登录</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Api from "@/api/User.js";
import { mapState } from "vuex";
import { Notification } from "element-ui";
export default {
  //import引入的组件需要注入到对象中才能使用
  name: "Login",
  components: {},
  data() {
    //这里存放数据
    var validateName = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入用户名"));
      } else {
        // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
        const userNameRule = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
        if (userNameRule.test(value)) {
          this.$refs.ruleForm.validateField("username");
          return callback();
        } else {
          return callback(
            new Error("字母开头,长度5-16之间,允许字母数字下划线")
          );
        }
      }
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z]\w{5,17}$/;
      console.log(passwordRule);

      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
          new Error("字母开头,长度6-18之间,允许字母数字和下划线")
        );
      }
    };
    return {
      Loginobj: {
        userName: "",
        password: ""
      },
      rules: {
        userName: [{ validator: validateName, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }]
      }
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    ...mapState(["loginDialog"])
  },
  //方法集合
  methods: {
    getLogin(ruleForm) {
      console.log(ruleForm);
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let { data: res } = await Api.getUserLogin({
            userName: this.Loginobj.userName,
            password: this.Loginobj.password
          });
          console.log(res);
          this.$store.state.user_id=res.user.user_id
          console.log( this.$store.state.user_id);
          
          if (res.code == "001") {
            Notification.success({ title: "成功", message: res.msg });
            const user = {
              userName: this.Loginobj.userName,
              password: this.Loginobj.password
            };
            var userLoginMsg = localStorage.setItem(
              "userNameLogin",
              JSON.stringify(user)
            );

            var users = JSON.parse(localStorage.getItem("userNameLogin"));
            this.$store.commit("onsubmit", users);
          }
        }
      });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
</style>